package cn.nit.blog.service.impl;

import cn.nit.blog.dto.CommentDto;
import cn.nit.blog.dto.IndexDataDto;
import cn.nit.blog.dto.MyPage;
import cn.nit.blog.entity.Comment;
import cn.nit.blog.entity.Post;
import cn.nit.blog.entity.User;
import cn.nit.blog.mapper.PostMapper;
import cn.nit.blog.service.IPostService;
import cn.nit.blog.utils.TimeAgoUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wjx
 * @since 2023-03-24
 */
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements IPostService {

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private LikeService likeService;

    @Override
    public MyPage<IndexDataDto> indexPost(MyPage<IndexDataDto> page, Integer orderMode) {
        MyPage<IndexDataDto> indexPostDtoMyPage = postMapper.indexPostVo(page, orderMode);
        List<IndexDataDto> records = indexPostDtoMyPage.getRecords();
        for (IndexDataDto record : records) {
            Post post = record.getPost();
            post.setCreateTimeStr(TimeAgoUtils.format(post.getCreateTime()));

            // 查询每个帖子的点赞数量
            Long count = likeService.likeSize(post.getId(), 1);
            post.setLikeCount(count);
        }
        return indexPostDtoMyPage;
    }

    @Override
    public IndexDataDto findPostDetail(Integer id) {
        return postMapper.findPostDetail(id);
    }

    @Override
    public List<CommentDto> getCommentListByPostId(Integer id) {
        List<CommentDto> commentDtos = postMapper.getCommentListByPostId(id);
        for (CommentDto commentDto : commentDtos) {
            Comment comment = commentDto.getComment();

//            设置时间格式的转换
            comment.setCreateTimeStr(TimeAgoUtils.format(comment.getCreateTime()));

            // 查询每个评论的点赞状态和状态数量
            Long count = likeService.likeSize(comment.getId(), 2);
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            User loginUser = (User) requestAttributes.getRequest().getSession().getAttribute("loginUser");
            boolean isLike = false;
            if (loginUser != null) {
                isLike = likeService.isLike(comment.getId(), 2, loginUser.getId());
            }
            commentDto.setLikeCount(count);
            commentDto.setLikeStatus(isLike ? 1L : 0L);
        }
        return commentDtos;
    }
}
